const express = require('express')
const { queryDB } = require('../db/db.js')

const userRouter = express.Router()

/**
 * 注册
 */
userRouter.post('/register', (req, res) => {
	const username = req.body.username
	const password = req.body.password
	const age = req.body.age
	const sex = req.body.sex

	// 检查用户名是否已经注册
	const sql1 = `SELECT count(*) AS num FROM users WHERE username = '${username}'`
	queryDB(sql1, results => {
        
		if (results[0].num > 0) {
			res.send({
				code: -1,
				message: '用户已经注册',
			})
		} else {
			// 保存到数据库
			const sql = `INSERT INTO users (username,password,age,sex)VALUES('${username}','${password}',${age},'${sex}')`
			queryDB(sql, results => {
				console.log(results)
				res.send({
					code: 1,
					message: '注册用户成功!',
				})
			})
		}
	})
})

/**
 * 登录
 */
userRouter.post('/login',(req,res)=>{
    const username = req.body.username
    const password = req.body.password

    const sql = `SELECT count(*) AS num FROM users WHERE username='${username}' AND password='${password}'`
    queryDB(sql,(results)=>{
        if(results[0].num>0){
            res.send({
                code:1,
                message:'登录成功!'
            })
        }else{
            res.send({
                code:-1,
                message:'用户名或密码出错!'
            })
        }
    })
})

module.exports = { userRouter }
